
import Foundation
import PerfectHTTP
import PerfectHTTPServer
import PerfectCrypto
import PerfectMySQL

func db(_ execute:(_ mysql:MySQL?)->()) {
  let mysql = MySQL()
  
  let host = "172.17.0.15"
  let port = 13306
  let user = "root"
  let password = "txdb818283TXDB"
  let db = "log"

  let connected = mysql.connect(host: host, user: user, password: password, db: db, port: UInt32(port))
  
  execute(connected ? mysql : nil)
}

var routes = Routes()

func add(request: HTTPRequest, response: HTTPResponse) {
    db { (conn) in
      if let conn = conn {
        if let app = request.param(name: "app"),
            let level = request.param(name: "level"),
            let message = request.param(name: "message"),
            let device = request.param(name: "device") {
          conn.query(statement: "insert into list (app, level, message, device) values (\"\(app)\",\(level),\"\(message)\",\"\(device)\")")
          
          response.setBody(string: "{ \"code\":0}")
          response.completed()
        } else {
          response.setBody(string: "{ \"code\":2}")
          response.completed()
        }
      } else {
        response.setBody(string: "{ \"code\":1}")
        response.completed()
      }
    }
}

struct LogItem : Encodable {
    var id:Int
    var level:Int
    var message:String
    var device:String
    var time:String
}

func list(request: HTTPRequest, response: HTTPResponse) {
    db { (conn) in
      if let conn = conn {
        let level = request.param(name: "level") ?? "0"
        if let app = request.param(name: "app"),
            let device = request.param(name: "device") {
            if conn.query(statement: "select id, message, time, level from list where app = \"\(app)\" and level >= \(level) and device=\"\(device)\" order by time desc limit 100") {
                let results = conn.storeResults()!
                response.setBody(string: "[")
                var isFirst = true
                while (true) {
                    if let value = results.next() {
                        let id = value[0]!
                        let message = value [1]!
                        let time = value[2]!
                        let level = value[3]!
                        if !isFirst {
                            response.appendBody(string: ",")
                        }
                        isFirst = false
                        response.appendBody(string: "{")
                        response.appendBody(string: "\"id\":\(id),")
                        response.appendBody(string: "\"level\":\(level),")
                        response.appendBody(string: "\"time\":\"\(time)\",")
                        response.appendBody(string: "\"message\":\"\(message)\"")
                        response.appendBody(string: "}")
                    } else {
                        break;
                    }
                }
                response.appendBody(string: "]")
                response.completed();
                return
            }
          
                response.setBody(string: "{ \"code\":2}")
                response.completed()
            
        } else {
            response.setBody(string: "{ \"code\":3}")
            response.completed()
        }
      } else {
        response.setBody(string: "{ \"code\":1}")
        response.completed()
      }
    }
}


routes.add(method:.get, uri: "/add", handler: add)
routes.add(method:.get, uri: "/list", handler: list)


try HTTPServer.launch(name: "115.159.159.203",
port: 8195,
routes: routes,
responseFilters: [
  (PerfectHTTPServer.HTTPFilter.contentCompression(data: [:]), HTTPFilterPriority.high)])

